<?php

class IssueController extends GeanyController {

    // <editor-fold defaultstate="collapsed" desc="STATIC & PRIVATE VARIABLE DECLARATION">
    private $validator;
    const _FUNCTION_ID = 'issue';
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CONSTRUCTOR">
  
    public function __construct(){
        parent::__construct();
        $this->loadDefaultValue();
        $this->loadServices();
        $this->validator = null;
    }
	
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="ACTION-HANDLER">
  
    public function index(){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        $data['Model'] = $this->mService->getList();

        return View::make('issue/index', $data);
	}
    
    public function create(){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }

        $input = Input::all();
        $issue = new Issue();
        try {
            if($input==null){
                return $this->createInputView($issue);
            }
            else{
                $issue = $this->bindData();
            if($this->validateInput($input)==FALSE) return $this->createInputView($issue);
                $newIssueId = $this->mService->insertObject($issue);
                if($newIssueId!=null){
                    Return Redirect::to('issue/detail/'.$newIssueId);
                }

                return $this->createInputView($issue);
            }
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            return $this->createInputView($this->bindData());
        }

    }


    public function edit($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }

        $input = Input::all();
        $issue = new Issue();
        try {
            if($input==null){
                $issue = $this->mService->getObject($id);
                return $this->createInputView($issue);
            }
            else{
                $issue = $this->bindData();
                if($this->validateInput($input)==FALSE) return $this->createInputView($issue);
                if($this->mService->updateObject($issue,$id)==true){
                    Return Redirect::to('issue/detail/'.$issue->getId());
                }
                return $this->createInputView($issue);
            }
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            return $this->createInputView($this->bindData());
        }
        
    }
    
    public function detail($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }

        $result = $this->mService->getObject($id);

        $input = Input::all();
        
        try {
            if($result==null) {
                PageData::addModelError("Issue [ ".$id." ] Not Found ");
                Return Redirect::to('issue')->with('ModelState',PageData::getModelState());
            }
            $data['Model'] = $result;
            
            if($input!=null){
                $Comment = $this->bindDataComment();
                $CommentDao = new CommentDao();
                
                if($CommentDao->insertObject($Comment)!=null){
                    PageData::addModelError("Error Add Comment");
                    Return Redirect::to('issue/detail/'.$id);
                }
            }
            
            return View::make('issue/detail', $data);
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            Return Redirect::to('issue')->with('ModelState',PageData::getModelState());
        }
    }
  
    public function done($id){
        if($this->mService->updateStatus("Done",$id)){
            PageData::addModelError("Error Update Status");
        }
            Return Redirect::to('issue/detail/'.$id);
    }
    

    private function loadComboPriority($show_all = false){
        $arr_data = array();

        $priorityService = new PriorityService();
        $priorities = $priorityService->getList();
        
        foreach($priorities as $item){
            $arr_data[$item->getName()] = $item->getName();
        }

        $this->data['PriorityCombo'] = $arr_data;
        
    }
    
    private function loadComboStatus($show_all = false){
        $arr_data = array();

        $statusService = new StatusService();
        $result = $statusService->getList();
        
        foreach($result as $item){
            $arr_data[$item->getName()] = $item->getName();
        }

        $this->data['StatusCombo'] = $arr_data;
        
    }
    
    
    private function loadComboTask($show_all = false){
        $arr_data = array();

        $taskService = new TaskService();
        $result = $taskService->getList();
        
        foreach($result as $item){
            $arr_data[$item->getName()] = $item->getName();
        }

        $this->data['TaskCombo'] = $arr_data;
        
    }
    
    private function createInputView($issue=null){
        $this->loadComboPriority();
        $this->loadComboStatus();
        $this->data['Model'] = $issue;
        return View::make('issue/input', $this->data);
    }
    
    private function bindData(){
        $data = Input::all();
        
        $issue = new Issue();
        $issue->setName($data["name"]);
        $issue->setDescription($data["description"]);
        $issue->setStart_date($data["start_date"]);
        $issue->setDue_date($data["due_date"]);
        
        $priority = new Priority();
        $priority->setId($data["priority"]);
        $issue->setPriority($priority);
        
//        $task = new Task();
//        $task->setId($data["Task_id"]);
        $issue->setTask_id($data["task_id"]);
        
        
        $status = new Status();
        $status->SetId($data["status_id"]);
        $issue->setStatus_id($status);
        
        $user = new User();
        $user->SetId($data["created_by"]);
        $issue->setCreated_by($user);
        
        $last_user = new User();
        $last_user->SetId($data["created_by"]);        
        $issue->setLast_update_by($last_user);
        
        $issue->setCreated_date($data["created_date"]);
        $issue->setLast_update_date($data["last_update_date"]);

        return $issue;
    }

    private function bindDataComment(){
        $data = Input::all();
        $Comment = new Comment();
        
            $issue = new Issue();
            $issue->setId($data['issue_id']);
            $issue->setIsLoaded(true);
            $Comment->setIssue($issue);
            
            $createdby = new User();
            $createdby->setId($this->userInformation()->getId());
            $createdby->setIsLoaded(true);
            $Comment->setEmployee($createdby);
            
            $Comment->setCreatedDate(date("Y/m/d"));
            
            $Comment->setCommentDetail($data['name']);
            
            $Comment->setIsLoaded(true);
            
        return $Comment;
    }
    
    private function validateInput($data){
                
        if($data==null) return false;
        $rules = array(
            'name' => 'alpha|required',
            'description' => 'required',
            'start_date' => 'date|required',
            'due_date' => 'date|required',
            'priority' => 'required',
//            'task_id' => 'required',
            'status_id' => 'required',
            'crated_by' => 'required',
            'crated_date' => 'required',
            'last_update_by' => 'required',
            'last_update_date' => 'required',
            
        );

        $messages = array(
            'name' => 'fill this field',
            'description' => 'fill this field',
            'start_date' => 'fill this field',
            'due_date' => 'fill this field',
            'priority' => 'fill this field',
//            'task_id' => 'fill this field',
            'status_id' => 'fill this field',
            'crated_by' => 'fill this field',
            'crated_date' => 'fill this field',
            'last_update_by' => 'fill this field',
            'last_update_date' => 'fill this field',
        );
        
        
        $this->validator = Validator::make($data, $rules, $messages);
        if($this->validator->fails()) PageData::assignValidatorToModelState ($this->validator);
        return $this->validator->passes();
    }
    
    
    private function loadDefaultValue(){
        $this->setFunctionId(self::_FUNCTION_ID);
        $this->page_data['_MODULE_NAME'] = $this->getFunctionName();
    }
    
    private function loadServices(){
        $this->mService = new IssueService();
    }
    
    // </editor-fold>
    
    
}
?>